//
//  ReaderFileViewController.m
//  Reader
//
//  Created by Kiran Panesar on 15/10/2014.
//
//

#import "ReaderFileViewController.h"
#import "ReaderViewController.h"
#import "UIViewController+WSJLodingView.h"
#import "UIImage+SQExtension.h"

#import "JCDownloader.h"
#import "JFFileManager.h"
#import "JCAlertView.h"

#import "AppDelegate.h"
#import <UMMobClick/MobClick.h>
#import "CKHttpCommunicate.h"
#import "HELPDFfileCacheTool.h"

@interface ReaderFileViewController () <ReaderViewControllerDelegate,UIAlertViewDelegate>


@property (nonatomic,  strong) JCDownloadOperation *operation;


@property (nonatomic,  assign) NSInteger studiedSeqNum;


@property (nonatomic,  strong) MBProgressHUD *bar;


@end

@implementation ReaderFileViewController

#pragma mark ReaderViewControllerDelegate

- (void)dismissReaderViewController:(ReaderViewController *)viewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame =CGRectMake(0, 0, 16, 28);
    [btn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back =[[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.leftBarButtonItem = back;
   [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:kMainColor] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
//    [[UINavigationBar appearance] setTintColor:kMainColor];
    
    
    if (self.isFromMyDownload ==YES) {
        [self preparePdfWithFilePath:[HELPDFfileCacheTool getDownloadPathWithPdfName:self.pdfName]];
        return;
    }
    
// 没有网络的时候
    weakSelf_define;
    HELNetworkStatus statues =[HELNetworkManager sharedMg].netStatus;
    if (statues == 0) {
        NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.pdfName];
        if (filePath) {
            
            NSNumber *page =  [HELPDFfileCacheTool getLastPageFromKey:self.pdfName];
            if (page) {
                self.studiedSeqNum =[page integerValue];
            }else{
                self.studiedSeqNum = 1;
            }
            
            [self preparePdfWithFilePath:filePath];
            return ;
        }else{
          
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"当前pdf并未缓存在本地" ButtonType:1 ButtonTitle:@"返回" Click:^{
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }];
        }
        return;
    }
    
    // 网络正常直接请求进度
    [self getPdfUrl];
   
}


- (void)backAction{
    
//    weakSelf_define;
    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认退出并保存进度" delegate:self cancelButtonTitle:@"继续学习" otherButtonTitles:@"退出并保存",nil];
    [alerView show];
   
//    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否确认退出并保存进度" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"继续学习" Click:nil ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"退出并保存"  Click:^{
//        [weakSelf uploadLearnProgress];
//    }];
  
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==1) {
        [self uploadLearnProgress];
    }
}

- (void)uploadLearnProgress{
   
//    这里还需要判断下是否已经完成过学习 ,完成过则不需要请求
   
    defineWeakSelf;
    [self dismissViewControllerAnimated:YES completion:^{
        
        if (_readerViewController.isFinished == YES) {
         //本地 进度更新 为总页数
            [HELPDFfileCacheTool saveLastPage:[_readerViewController.document.pageCount integerValue] withPdfKey:weakSelf.pdfName];
//            alertMessage(@"课程完结,不请求啦~");
            return ;
        }
        
        NSMutableDictionary *params =[NSMutableDictionary
                                    dictionary];
        weakSelf_define;
        params[@"userId"] = HEL_USERID;
        params[@"seqNum"] =@(_readerViewController.maxReadPage);
        params[@"tblStudyDataId"] =@(self.courseId);
        [[HELNetworkManager sharedMg] GET:kUploadLearningProgress parameters:params success:^(NSDictionary *responseObject) {
            
            if (responseObject[@"exception"]) {
                alertMessage(responseObject[@"exception"]);
            }else{
                NSString *str =[NSString stringWithFormat:@"保存成功, 您学习到第%li页",(long)_readerViewController.maxReadPage];
                  [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.pdfName];
                alertMessage(str);
                 [MobClick event:@"StudyCount" label:deviceName];
                if (weakSelf.callBack) {
                    weakSelf.callBack();
                }
                
            }
            
        } failure:^(NSString *err) {
             [HELPDFfileCacheTool saveLastPage:_readerViewController.maxReadPage withPdfKey:weakSelf.pdfName];
        }];
    }];
}


#pragma mark -请求pdf下载网址
- (void)getPdfUrl{
    
//    "pdfName": "20160526152414_70164695-113d-4634-acbb-2fd99ebed9d4.pdf",
//    "pdfUrl": "http://exam.hulijia365.com:80/scmcstudy/upload/sdimg/20160526152414_70164695-113d-4634-acbb-2fd99ebed9d4.pdf",
//    "studiedSeqNum": 28
    
//    [self wsj_showLodingGif];
    cwqHud(self.view);
   
    
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"tblStudyDataId"] =@(self.courseId);
    params[@"userId"] =HEL_USERID;
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:kDownloadPdf parameters:params success:^(NSDictionary * responseObject) {
//        [weakSelf wsj_hideLodingGif];
        [hud hideAnimated:YES];
        if (responseObject[@"exception"]) {
             alertMessage(responseObject[@"exception"]);
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        if (responseObject[@"pdfUrl"]) {
            weakSelf.urlStr =responseObject[@"pdfUrl"];
            weakSelf.pdfName =responseObject[@"pdfName"];
            
            NSNumber *page =  [HELPDFfileCacheTool getLastPageFromKey:weakSelf.pdfName];
            if (page) {
               
                weakSelf.studiedSeqNum =MAX([page integerValue], [responseObject[@"studiedSeqNum"] integerValue]);
            }else{
                weakSelf.studiedSeqNum =[responseObject[@"studiedSeqNum"] integerValue];
            }
            //更新本地进度
            [HELPDFfileCacheTool saveLastPage:weakSelf.studiedSeqNum withPdfKey:weakSelf.pdfName];
            [weakSelf downPdfFile];
        }
        
    } failure:^(NSString *err) {
//         [weakSelf wsj_hideLodingGif];
         [hud hideAnimated:YES];
        alertMessage(@"下载出错");
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        
    }];
    
    
}
- (void)dealloc{


}
//
//- (void)downdloadPdfFile{
//    
//    weakSelf_define;
//    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
//    hud.animationType = MBProgressHUDAnimationZoomOut;
//    hud.label.text = @"正在下载...";
//    hud.progress = 0;
//    [hud showAnimated:YES];
//
//   
//    //下载放置的位置
//   NSString *cachesPath= [JFFileManager documentsDirectory];
//
// 
//   NSString *downDesPath =[cachesPath stringByAppendingPathComponent:self.pdfName];
//
//    JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
//    downloadItem.downloadUrl = self.urlStr;
//    downloadItem.downloadFilePath = downDesPath;
//    
//    self.operation = [JCDownloadOperation operationWithItem:downloadItem];
//    [self.operation startWithProgressBlock:^(NSProgress *progress) {
////        CGFloat i =(progress.completedUnitCount *1.0 )/(progress.totalUnitCount *1.0);
//        CGFloat i = progress.completedUnitCount;
//        CGFloat p =progress.totalUnitCount;
//        hud.progress = (i * p)/p -1;
//        //update progress
//    } completionBlock:^(NSURL *filePath, NSError *error) {
//        //download operation completion, do something
//        [hud hideAnimated:YES];
//        if (error) {
//            alertMessage(error.localizedDescription);
//        }
//        NSString *fullPath = [filePath path];
//        [weakSelf preparePdfWithFilePath:fullPath];
//      
//    }];
//
////    [self.operation pauseDownload];
////    [self.operation removeDownload];
////    [self.operation startDownload];
//
//}
//



- (void)downPdfFile{
    
//    
//    NSFileManager *fm = [NSFileManager defaultManager];
//    //huo
////    NSString *fileName =[[NSUserDefaults standardUserDefaults] objectForKey:self.pdfNameShow];
//    NSString *home = NSHomeDirectory();
//    NSString *documentsPath = [home stringByAppendingPathComponent:@"Documents"];
//    NSString *filePath =[documentsPath stringByAppendingPathComponent:self.pdfName];
//    
//    if ([fm fileExistsAtPath:filePath]) {
//        [self preparePdfWithFilePath:filePath];
//        return;
//    }
//    if (filePath) {
//        
//    }
//
    NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:self.pdfName];
    if (filePath) {
        [self preparePdfWithFilePath:filePath];
        return ;
    };
    weakSelf_define;
   
    __block MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    hud.animationType = MBProgressHUDAnimationZoomOut;
    hud.label.text = @"正在下载...";
    hud.progress = 0;
    [hud showAnimated:YES];
    self.bar = hud;
  

   
    [CKHttpCommunicate createDownloadFileWithURLString:self.urlStr downloadFileProgress:^(NSProgress *progress) {
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            hud.progress = progress.fractionCompleted;
            hud.label.text = [NSString stringWithFormat:@"已下载%.f%%",progress.fractionCompleted *100];
        });
       
//        NSLog(@"---%f,%f",progress,progress.completedUnitCount);
        
    } setupFilePath:^NSURL *(NSURLResponse *response) {
        
//        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
       
        return [NSURL fileURLWithPath: [HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.pdfName]];
        
    } downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        
        if (error) {
            alertMessage(error.localizedDescription);
        }
        NSString *fullPath = [filePath path];
        [weakSelf preparePdfWithFilePath:fullPath];

        [hud hideAnimated:YES];

    }];
    
    


 
}

- (void)preparePdfWithFilePath:(NSString *)path{
   
    
    ReaderDocument *document = [[ReaderDocument alloc] initWithFilePath:path
                                                               password:nil];
    
    _readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];

    _readerViewController.lastPage =self.studiedSeqNum;
    [_readerViewController setDelegate:self];
    
    //    [_readerViewController setRemoteNavigationItem:self.navigationItem];
    [_readerViewController setRemoteNavigationController:self.navigationController];
    if (document.pageCount.integerValue == self.studiedSeqNum) {
         _readerViewController.isFinished = YES;
    }else{
     _readerViewController.isFinished = NO;
    }
   
    
    [self.view addSubview:_readerViewController.view];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_readerViewController viewWillAppear:animated];
   }

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [_readerViewController viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_readerViewController viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_readerViewController viewDidDisappear:animated];
   

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [_readerViewController willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
